package com.mt.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mt.enums.Status;
import com.mt.exception.GlobalException;
import com.mt.mapper.RoleMapper;
import com.mt.pojo.Acl;
import com.mt.pojo.Role;
import com.mt.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Wang
 * @since 2020-11-12
 */
@Service
public class
RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    RoleMapper roleMapper;

    @Override
    public Boolean addRole(Role role, List<Integer> aclIds) {
        //查看角色名重复
        Role r = roleMapper.selectOne(Wrappers.<Role>lambdaQuery().eq(Role::getRoleName, role.getRoleName()));
        if (r != null) {
            throw new GlobalException(Status.EXIST_USER);
        }
        roleMapper.insert(role);
        //角色分配权限
        Boolean acl4Role = roleMapper.distributeAcl4Role(role.getId(), aclIds);
        if (!acl4Role) {
            throw new GlobalException(Status.ERROR, "分配角色权限失败");
        }
        return true;
    }

    @Override
    public List<Acl> listAclByRole(Role role) {
        List<Acl> acls = roleMapper.listAclByRole(role.getId());
        return acls;
    }

    @Override
    @Transactional(rollbackFor = GlobalException.class)
    public Boolean modifyRole(Role role, List<Integer> newAclIds) {
        if ( roleMapper.deleteAclByRole(role.getId()) ){
            Boolean acl4Role = roleMapper.distributeAcl4Role(role.getId(), newAclIds);
            if (!acl4Role) {
                throw new GlobalException(Status.ERROR, "分配角色权限失败");
            }
        }
        return true;
    }


}
